package whf.shop.web;

import java.util.List;

import whf.framework.entity.AbstractEntity;
import whf.framework.util.Pair;
import whf.framework.util.Utils;
import whf.framework.web.struts.WebData;
import whf.framework.web.struts.WebDispatchAction;
import whf.framework.web.struts.WebForward;
import whf.shop.entity.Order;
import whf.shop.entity.Product;
import whf.shop.service.ProductService;
import whf.shop.service.ProductServiceImp;
import whf.shop.utils.ShopUtils;

/**
 * @author wanghaifeng
 * @email king@126.com
 * @modify 2007-01-11
 */
public class OrderAction extends WebDispatchAction {

	//-----------------
	public WebForward addProducts(AbstractEntity baseForm, WebData data) throws Exception {
		Order order = ShopUtils.getCurrentOrder(data.getSession());
		long[] productIds = data.getLongParameters("pid", 0);
		ProductService ps = ProductServiceImp.getProductService();
		List<Pair<Product, Integer>> products = Utils.newArrayList();
		if(productIds != null)
			for(long pid : productIds){
				if(pid == 0) continue;
				int quantity = data.getIntParameter("q_" + pid, 1);
				Product product = ps.findByPrimaryKey(pid);
				products.add(new Pair<Product, Integer>(product, new Integer(quantity)));
			}
		if(!products.isEmpty()){
			order.addProducts(products);
		}
		return data.forward("viewMyCart");
	}
	
	/**
	 * 向订单中增加一个产品
	 * @modify wanghaifeng Mar 31, 2007 1:36:32 PM
	 * @param baseForm
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public WebForward resetProducts(AbstractEntity baseForm, WebData data) throws Exception {
		Order order = ShopUtils.getCurrentOrder(data.getSession());
		long[] productIds = data.getLongParameters("pid", 0);
		ProductService ps = ProductServiceImp.getProductService();
		List<Pair<Product, Integer>> products = Utils.newArrayList();
		if(productIds != null)
			for(long pid : productIds){
				if(pid == 0) continue;
				int quantity = data.getIntParameter("q_" + pid, 0);
				Product product = ps.findByPrimaryKey(pid);
				products.add(new Pair<Product, Integer>(product, new Integer(quantity)));
			}
		if(!products.isEmpty()){
			order.resetProductQuantity(products);
		}
		return data.forward("viewMyCart");
	}
	
	public WebForward viewMyCart(AbstractEntity baseForm, WebData data) throws Exception {
		return data.forward("viewMyCart");
	}
	
	public WebForward removeFromCart(AbstractEntity baseForm, WebData data) throws Exception {
		Order order = ShopUtils.getCurrentOrder(data.getSession());
		long[] productIds = data.getLongParameters("pid", 0);
		for(int i=0; productIds != null && i < productIds.length; i++){
			long pid = productIds[i];
			if(pid == 0) continue;
			Product p = ((ProductService)super.getService()).findByPrimaryKey(pid);
			order.removeOrderItem(p);
		}
		return data.forward("viewMyCart");
	}
}